package cc.mcggdd.leah.boot.stock.controller;

import cc.mcggdd.leah.boot.stock.model.entity.StockBill;
import cc.mcggdd.leah.boot.stock.model.entity.StockDebt;
import cc.mcggdd.leah.boot.stock.model.vo.StockBillReportItemVO;
import cc.mcggdd.leah.boot.stock.model.vo.StockBillReportVO;
import cc.mcggdd.leah.boot.stock.service.StockBillService;
import cc.mcggdd.leah.boot.stock.service.StockDebtService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cc.mcggdd.leah.boot.stock.model.form.StockBillForm;
import cc.mcggdd.leah.boot.stock.model.query.StockBillQuery;
import cc.mcggdd.leah.boot.stock.model.vo.StockBillVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import cc.mcggdd.leah.boot.common.result.PageResult;
import cc.mcggdd.leah.boot.common.result.Result;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 账单前端控制层
 *
 * @author 
 * @since 2025-02-10 14:57
 */
@Tag(name = "账单接口")
@RestController
@RequestMapping("/api/v1/stockBills")
@RequiredArgsConstructor
public class StockBillController  {

    private final StockBillService stockBillService;
    private final StockDebtService stockDebtService;

    @Operation(summary = "账单分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPerm('stock:stockBill:query')")
    public PageResult<StockBillVO> getStockBillPage(StockBillQuery queryParams ) {
        IPage<StockBillVO> result = stockBillService.getStockBillPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "新增账单")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('stock:stockBill:add')")
    public Result<Void> saveStockBill(@RequestBody @Valid StockBillForm formData ) {
        boolean result = stockBillService.saveStockBill(formData);
        return Result.judge(result);
    }

    @Operation(summary = "获取账单表单数据")
    @GetMapping("/{id}/form")
    @PreAuthorize("@ss.hasPerm('stock:stockBill:edit')")
    public Result<StockBillForm> getStockBillForm(
        @Parameter(description = "账单ID") @PathVariable Long id
    ) {
        StockBillForm formData = stockBillService.getStockBillFormData(id);
        return Result.success(formData);
    }

    @Operation(summary = "修改账单")
    @PutMapping(value = "/{id}")
    @PreAuthorize("@ss.hasPerm('stock:stockBill:edit')")
    public Result<Void> updateStockBill(
            @Parameter(description = "账单ID") @PathVariable Long id,
            @RequestBody @Validated StockBillForm formData
    ) {
        boolean result = stockBillService.updateStockBill(id, formData);
        return Result.judge(result);
    }

    @Operation(summary = "删除账单")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('stock:stockBill:delete')")
    public Result<Void> deleteStockBills(
        @Parameter(description = "账单ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = stockBillService.deleteStockBills(ids);
        return Result.judge(result);
    }

    @Operation(summary = "待还账单")
    @GetMapping("/report")
    @PreAuthorize("@ss.hasPerm('stock:stockBill:query')")
    public Result<StockBillReportVO> getStockBillsReport(
    ) {
        StockBillReportVO reportVO = new StockBillReportVO();

        LocalDate maxDate = stockBillService.getRepayMaxDate();
        LocalDate lastOfMaxDate = maxDate.with(TemporalAdjusters.lastDayOfMonth());

        List<String> monthList = new ArrayList<>();
        reportVO.setMonths(monthList);
        LocalDate tempDate = LocalDate.now();
        while(true){
            monthList.add(String.format("%d-%02d", tempDate.getYear(), tempDate.getMonthValue()));
            tempDate = tempDate.plusMonths(1);
            if( tempDate.compareTo(lastOfMaxDate) > 0)
                break;
        }

        List<StockDebt> debtRecords = stockDebtService.getAllRecord();
        Map<Long, String> debtMap = new HashMap<>();
        for (StockDebt stockDebt : debtRecords) {
            debtMap.put(stockDebt.getId(), stockDebt.getSubject());
        }
        
        List<String> legends = new ArrayList<>();
        List<StockBillReportItemVO> monthData = new ArrayList<>();
        reportVO.setLegend(legends);
        reportVO.setMonthData(monthData);
        
        List<StockBill> billRepayRecords = stockBillService.getAllRecord("N");
        Long debtId = 0L;
        StockBillReportItemVO itemVO = null;
        Map<String, BigDecimal> itemDataMap = null;
        for (StockBill bill : billRepayRecords) {
            if (bill.getDebtId() != debtId) {  // 换到下一个负债时, 重新创建一个报表项
                if(itemVO != null) {
                    List<BigDecimal> data = new ArrayList<>();
                    for (BigDecimal value : itemDataMap.values()) {
                        data.add(value);
                    }
                    itemVO.setData(data);
                }
                
                legends.add(debtMap.get(bill.getDebtId()));
                debtId = bill.getDebtId();
                itemVO = new StockBillReportItemVO();
                itemVO.setName(debtMap.get(bill.getDebtId()));
                itemVO.setType("line");
                monthData.add(itemVO);
                itemDataMap = new HashMap<>();
                for (String month : monthList) {
                    itemDataMap.put(month, BigDecimal.ZERO);
                }
            }
            itemDataMap.put(String.format("%d-%02d", bill.getBillDate().getYear(), bill.getBillDate().getMonthValue()), bill.getBillAmount());
        }
        List<BigDecimal> data = new ArrayList<>();
        for (BigDecimal value : itemDataMap.values()) {
            data.add(value);
        }
        itemVO.setData(data);
        
        return Result.success(reportVO);
    }
}
